package com.zlz.open.dict.controller;

import com.zlz.base.entity.response.PageInfo;
import com.zlz.base.entity.response.ResultSet;
import com.zlz.base.enums.DefaultStatusEnum;
import com.zlz.base.exception.BizException;
import com.zlz.open.dict.bean.dos.DictGroupEntity;
import com.zlz.open.dict.bean.request.DictGroupRequest;
import com.zlz.open.dict.bean.request.DictValueRequest;
import com.zlz.open.dict.bean.vo.DictGroupResponse;
import com.zlz.open.dict.service.DictGroupService;
import com.zlz.open.dict.service.DictValueService;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/dict")
public class DictController {

    private final DictGroupService dictGroupService;

    private final DictValueService dictValueService;

    public DictController(DictGroupService dictGroupService, DictValueService dictValueService) {
        this.dictGroupService = dictGroupService;
        this.dictValueService = dictValueService;
    }

    @PostMapping(value = "/group/create")
    public Mono<ResultSet<Long>> create(@RequestBody Mono<DictGroupRequest> request) {
        return dictGroupService.createGroup(request);
    }

    @PostMapping("/group/selectPage")
    public Mono<ResultSet<PageInfo<DictGroupResponse>>> selectPage(@RequestBody Mono<DictGroupRequest> request) {
        return dictGroupService.findByPage(request);
    }

    @PostMapping("/group/update")
    public Mono<ResultSet<Boolean>> updateGroup(@RequestBody Mono<DictGroupRequest> request) {
        return dictGroupService.updateGroup(request);
    }

    @GetMapping("/group/delete/{code}")
    public Mono<ResultSet<Boolean>> deleteGroup(@PathVariable String code) {
        DictGroupEntity dictGroupEntity = dictGroupService.selectByCode(code);
        if (DefaultStatusEnum.DEFAULT.getCode().equals(dictGroupEntity.getIsDefault())) {
            throw new BizException("默认字典不允许删除");
        }
        DictValueRequest request = new DictValueRequest();
        request.setGroupCode(code);
        return dictGroupService.deletedGroup(
                dictValueService.deletedValue(Mono.just(request))
                        .filter(ResultSet::isSuccess)
                        .switchIfEmpty(Mono.error(new BizException("删除失败")))
                        .map((rs) -> code));
    }

}
